<?php

class BoxesPage extends BaseAdminPage {

	/**
	 * Az összes doboz rekord
	 */
	private $allBoxRecords;

	/**
	 * A szerkesztés alatt álló doboz azonosítója. 
	 */
	private $editedBoxId;

	/**
	 * A doboz stílusok tömbje. 
	 */
	private $boxStyleArray;

	/**
	 * A doboz helyének tömbje. 
	 */
	private $boxPlaceArray;

	/**
	 * Újonnan létrehozott doboz szerkesztése folyik-e.
	 */
	private $isnew;


	function BoxesPage() {
		parent::BaseAdminPage("BoxesPage");
	}

	function enterPage()
	{
		parent::enterPage();

		$this->boxStyleArray = ConstHandler::get("BOX_CSS");
		$_SESSION["_boxStyleArray"] = $this->boxStyleArray;
		
		$this->boxPlaceArray = ConstHandler::get("BOX_PLACES");
		$_SESSION["_boxPlaceArray"] = $this->boxPlaceArray;

		// definiáljuk a form elemeit
		FormUtil::addForm("box");
		FormUtil::addFormElement("box", new FormElementInfo("id", "text", null));
		FormUtil::addFormElement("box", new FormElementInfo("name", "text", null));
		//FormUtil::addFormElement("box", new FormElementInfo("closed", "checkbox", null));
		//FormUtil::addFormElement("box", new FormElementInfo("closable", "checkbox", null));
		FormUtil::addFormElement("box", new FormElementInfo("noheader", "checkbox", null));
		FormUtil::addFormElement("box", new FormElementInfo("height", "text", null));
		FormUtil::addFormElement("box", 
			new FormElementInfo("css", 
					"select", 
					null, 
					array("arrayType"=>"simpleArray", "array" => $this->boxStyleArray, "translateLabels" => true)));
		FormUtil::addFormElement("box", 
			new FormElementInfo("place", 
					"select", 
					null, 
					array("arrayType"=>"simpleArray", "array" => $this->boxPlaceArray, "translateLabels" => true)));
	}


	function leavePage()
	{
		parent::leavePage();

		$this->_init();

		FormUtil::removeAllForms();

		unset($_SESSION["_bx_boxId"]);
		unset($_SESSION["_bx_isnew"]);

		unset($_SESSION["_boxStyleArray"]);
		unset($_SESSION["_boxPlaceArray"]);
	}

	/**
	 * Feltölti session-ből az aktuális működési változókat
	 */
	protected function _init()
	{
		$this->editedBoxId = FunctionLibrary::getSessionValue("_bx_boxId", null);
		$this->isnew = FunctionLibrary::getSessionValue("_bx_isnew", "0");
		$this->boxStyleArray = FunctionLibrary::getSessionValue("_boxStyleArray");
	}

	protected function getListPageLink()
	{
		return HydraLinkProvider::getLink('boxes');
	}

	/**
	 * Felolvassa a doboz rekordokat.
	 * Ez itt most úgy csinálja, hogy az aktuális nyelven létező referenciákra kíváncsi.
	 */
	protected function readAllBoxes()
	{
		$orderBy = array("place asc", "serial asc");
		$this->allBoxRecords = SiteDBHelper::getBoxes(AdminBase::getCurrentEditlang(), $orderBy);
	}


	public function serveRequest()
	{
		parent::serveRequest();

		$this->_init();
			
		$tpl = BaseAdminPage::loadTemplateFile(BOXES_TEMPLATE);
		TextHandler::insertTextsIntoTemplate($tpl, null, "bx_");
		$tpl->setVariable('app_root_url', APP_ROOT_URL);
		$tpl->setVariable('admin_tbl_opers', TextHandler::getText("admin_tbl_opers"));
		$tpl->setVariable('form_action', HydraLinkProvider::getLink('updateBox'));
		$tpl->setVariable("form_action_addbox", HydraLinkProvider::getLink('addBox'));
		$tpl->setVariable('but_add', TextHandler::getText("but_add"));

		// felnyaljuk a rekordokat
		$this->readAllBoxes();
		if(is_null($this->allBoxRecords))
		{
			// suxxx!
			handleError(TextHandler::getText('err_readrecordsfailed'));
			$tpl->replaceBlock('box', ' ', false);
			$tpl->touchBlock('box');
		}
		else
		{
			$action = FunctionLibrary::getGetOrPostValue('action');
			if($action)
			{
				$action = 'action_'.$action;
				$this->$action();
			}

			// megvannak a rekordok!
			if(count($this->allBoxRecords) == 0)
			{
				$tpl->replaceBlock('box', ' ', false);
				$tpl->touchBlock('box');
			}
			else
			{
				$count = 1;
				foreach($this->allBoxRecords as $boxRecord)
				{
					$boxContent = null;
					if ($boxRecord['id'] == $this->editedBoxId) {
						// feltöltjük a form-ot az objektumból, de ravaszul: csak első alkalommal!
						if(!FormUtil::hasFormInstance("box", "saved"))
						{
							// még nincs form instance, létrehozzuk!
							FormUtil::fillFormValuesFromObject("box", $boxRecord, "saved");
						}

						$editBoxTpl = BaseAdminPage::loadTemplateFile(EDITBOX_TEMPLATE);
						TextHandler::insertTextsIntoTemplate($editBoxTpl, null, "bx_");
						// a saved form instance-ból töltjük fel a sablon értékeit
						FormUtil::insertFormValuesToTemplate("box", $editBoxTpl, "saved");

						$editBoxTpl->setVariable('app_root_url', APP_ROOT_URL);
						$editBoxTpl->setVariable('but_save', TextHandler::getText('but_save'));
						$editBoxTpl->setVariable('but_cancel', TextHandler::getText('but_cancel'));
						$editBoxTpl->setVariable('cancelLink', HydraLinkProvider::getLink('cancelBox'));
						$editBoxTpl->setVariable("link_delbox", HydraLinkProvider::getLink('delBox', array("id"=>$boxRecord["id"])));
						
						$editBoxTpl->setVariable("id", $boxRecord['id']);

						$boxContent = $editBoxTpl->get();
					} else {
						$rawBoxTpl = BaseAdminPage::loadTemplateFile(RAWBOX_TEMPLATE);

						TextHandler::insertTextsIntoTemplate($rawBoxTpl, null, "bx_");
						$rawBoxTpl->setVariable('app_root_url', APP_ROOT_URL);

						$rawBoxTpl->setVariable("id", $boxRecord['id']);
						$rawBoxTpl->setVariable("name", $boxRecord['name']);
						if (isset($this->boxStyleArray[$boxRecord['css']])) {
							$rawBoxTpl->setVariable("css", TextHandler::getText($this->boxStyleArray[$boxRecord['css']]));
						} else {
							$rawBoxTpl->setVariable("css", "");
						}
						$places = ConstHandler::get("BOX_PLACES");
						$rawBoxTpl->setVariable("place", TextHandler::getText($places[$boxRecord['place']]));
						$rawBoxTpl->setVariable("link_editbox", HydraLinkProvider::getLink('editBox', array("id"=>$boxRecord["id"])));
						$rawBoxTpl->setVariable("link_edittabs", HydraLinkProvider::getLink('boxtabs', array("boxid"=>$boxRecord["id"])));
						
						$serial = $boxRecord['serial'];
						if ($serial == 1) {
							$rawBoxTpl->setVariable("hideForwardLink", "class=\"hiddenLink\" onclick=\"return false\"");
						} else {
							$rawBoxTpl->setVariable("hideForwardLink", "");
						}
						$rawBoxTpl->setVariable("link_moveForward", HydraLinkProvider::getLink('moveForward', array("id"=>$boxRecord["id"])));

						try {
							if(!AdminDBHelper::hasBoxAfter($boxRecord))
								$rawBoxTpl->setVariable("hideBackwardLink", "class=\"hiddenLink\" onclick=\"return false\"");
							else
								$rawBoxTpl->setVariable("hideBackwardLink", "");
						} catch (Exception $e) {
							$rawBoxTpl->setVariable("hideBackwardLink", "class=\"hiddenLink\" onclick=\"return false\"");
						}
						$rawBoxTpl->setVariable("link_moveBackward", HydraLinkProvider::getLink('moveBackward', array("id"=>$boxRecord["id"])));

						$rawBoxTpl->setVariable("link_delbox", HydraLinkProvider::getLink('delBox', array("id"=>$boxRecord["id"])));

						$boxContent = $rawBoxTpl->get();
					}
					$tpl->setCurrentBlock('box');
					$tpl->setVariable('box_content', $boxContent);
					$tpl->parseCurrentBlock();
					$count++;
				}
			}
			$tpl->parseCurrentBlock();
		}
			
		return $tpl->get();
	}

	/**
	 * Új doboz rekord hozzáadása
	 */
	private function action_addBox()
	{
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;

		try {
			$name = FunctionLibrary::getPostValue('name');
			if (empty($name)) {
				$errorStrings = array(TextHandler::getText('bx_err_name_empty'));
				handleError(TextHandler::getParsedText('bx_err_add_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
			} else {
				$boxId = AdminDBHelper::addBox($name, AdminBase::getCurrentEditlang(), SiteHandler::getCurrentSiteId());
	
				$editLink = HydraLinkProvider::getLink('editBox', array('id'=>$boxId, "isnew"=>"1"));
	
				// ha sikeres volt, akkor át is lépünk a szerkesztő oldalra, de azzal amegjegyzéssel h ez egy új doboz
				handleSuccess(TextHandler::getText("bx_added"), $editLink);
				exit();
			}
		} catch (Exception $e) {
			if (isset($boxId))
				$logErrorString = "adding box, id=$boxId failed";
			else
				$logErrorString = "adding box failed";
			$errorStrings = array($e->getMessage());
		}
			
		Log::error('following errors occured during operation:'.$logErrorString);
		handleError(TextHandler::getParsedText('bx_err_add_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
	}

	/**
	 * Szerkesztésre megnyitja a dobozt.
	 */
	private function action_editBox()
	{
		$this->isnew = FunctionLibrary::getGetValue("isnew");
		if (empty($this->isnew)) {
			unset($_SESSION["_bx_isnew"]);
			$this->isnew = "0";
		} else {
			$_SESSION["_bx_isnew"] = $this->isnew;
		}

		$this->editedBoxId = FunctionLibrary::getGetOrPostValue("id");
		if (empty($this->editedBoxId)) {
			unset($_SESSION["_bx_boxId"]);
			$errorStrings = array(TextHandler::getText("bx_err_boxnotfound"));
			handleError(TextHandler::getParsedText('err_op_failed', array("errors"=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
			exit();
		} else {
			$_SESSION["_bx_boxId"] = $this->editedBoxId;
			FormUtil::removeFormInstanceIfExists("box", "saved");
		}
	}

	/**
	 * Törli a dobozt.
	 */
	private function action_delBox()
	{
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;
			
		$id = FunctionLibrary::getGetOrPostValue('id');

		if(!is_null($id) && TextUtil::isStringInteger($id))
		{
			$id = intval($id);

			try {
				$record =& AdminDBHelper::delBox($id);
					
				handleSuccess(TextHandler::getParsedText("bx_removed", array('name' => $record['name'])), $this->getListPageLink());
				exit();
			} catch (MissingTableRowException $e) {
				$logErrorString = "removing box id=$id failed, no such record";
				$errorStrings = array(TextHandler::getText('bx_err_boxnotfound'));
			} catch (Exception $e) {
				$logErrorString = "removing box id=$id failed: ".$e->getMessage();
				$errorStrings = array($e->getMessage());
			}
		}
		else
		{
			$logErrorString = "required request parameter 'id' is missing or malformed";
		}
			
		Log::error('following errors occured during operation:'.$logErrorString);
		handleError(TextHandler::getParsedText('bx_err_remove_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
	}

	/**
	 * Cancel
	 */
	private function action_cancelBox()
	{
		$successMessage = null;
		if ($this->isnew == "1")
		{
			// vissza kell vonni a dobozt, nem mentették el

			$errorStrings = array(TextHandler::getText('err_unknown'));
			$logErrorString = null;

			$id = $this->editedBoxId;

			$doDelete = false;

			// szedjük vissza a rekordot! ez tömböt ad, tudod!
			$boxRecord = AdminDBHelper::getBox($id);
			if(is_null($boxRecord))
			{
				$doDelete = true;
			}
			else
			{
				if(count($boxRecord) > 0)
				{
					$doDelete = true;
				}
				else
				{
					// nincs mit törölni!
				}
			}

			if($doDelete)
			{
				try {
					AdminDBHelper::delBox($id);

					$successMessage = TextHandler::getText("bx_removed");

				} catch (Exception $e) {

					$logErrorString = "removing box id=$id failed: ".$e->getMessage();
					$errorStrings = array($e->getMessage());

					Log::error('following errors occured during operation:'.$logErrorString);
					handleError(TextHandler::getParsedText('bx_err_remove_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
				}
					
			}

		}
		// session ürítése
		unset($_SESSION["_bx_boxId"]);
		unset($_SESSION["_bx_isnew"]);
		FormUtil::removeFormInstanceIfExists("box", "saved");
		
		// visszalépünk a listára
		handleSuccess($successMessage, $this->getListPageLink());
		exit();
	}


	/**
	 * Doboz módosítása
	 */
	private function action_updateBox()
	{
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;

		// szedjük le a form értékeket
		FormUtil::fillFormValuesFromRequest("box", "saved");
		$formValues = FormUtil::getFormValues("box", "saved");
		$id = $formValues['id'];

		$formValues['place'] = intval($formValues['place']);
		
		$origBoxRecord = null;
		try {
			$origBoxRecord = AdminDBHelper::getBox($formValues['id']);
		} catch (Exception $e) {
		}

		// itt tranzakcióba fogunk mindent!
		$db = DBHandler::dbGet();
		$db->autoCommit(false);
		
		// mentés!
		if(!is_null($origBoxRecord))
		{
			try {
				
				// oké nézzük mi változik...
				$siteId = SiteHandler::getCurrentSiteId();
				$placeChanges = ($origBoxRecord['place'] != $formValues['place']);

				$langcode = $origBoxRecord['langcode'];
				
				if($placeChanges)
				{
					// az eddigi helyen mögötte lévőket előrébb húzzuk
					$statement = $db->prepare("update box set serial = serial - 1 where langcode = ? and site_id = ? and place = ? and serial > ?");
					$data = array($langcode, $siteId, $origBoxRecord['place'], $origBoxRecord['serial']);
					$result =& $db->execute($statement, $data);
					if (PEAR::isError($result)) {
						$msg = "failed to move forward boxes serials after desired box record due to db error: ".$result->getDebugInfo();
						Log::error($msg);
						MailHelper::sendAdminMail("db error occured", $msg);
						
						throw new Exception(TextHandler::getText("err_sql_error"));
					}
					
					// az új helyen meg kell tudnunk mi a mostani max serial, és úgy kell beállítani az újat
					$otherRecord = AdminDBHelper::getMaxBoxSerial($langcode, $formValues['place'], $siteId);
					if (is_null($otherRecord))
						$nextSerial = 1;
					else
						$nextSerial = $otherRecord['serial'] + 1;
					$formValues['serial'] = $nextSerial;
				}

				// oksa, és most mehet a módosítás 
				AdminDBHelper::modBox($formValues);
	
				// session ürítése
				unset($_SESSION["_bx_boxId"]);
				unset($_SESSION["_bx_isnew"]);
				FormUtil::removeFormInstanceIfExists("box", "saved");
	
				// ha sikeres volt, akkor megyünk vissza a listára!
				$db->commit();
				$db->autoCommit(true);
				
				
				handleSuccess(null, $this->getListPageLink());
				exit();
	
			} catch (Exception $e) {
	
				$logErrorString = "modifying box id=$id failed";
				$errorStrings = array($e->getMessage());
			}
		}
		else
		{
			$logErrorString = "box with id=$id not found, modification skipped!";
			$errorStrings = array(TextHandler::getText("bx_err_boxnotfound"));
		}
		 
		// bármit is csináltunk, azt visszavonjuk!
		$db->rollback();
		$db->autoCommit(true);
		
		Log::error('following errors occured during operation:'.$logErrorString);
		handleError(TextHandler::getParsedText('bx_err_modify_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), HydraLinkProvider::getLink('editBox', array('id'=>$id, "isnew"=>$this->isnew)));
	}

	/**
	 * Doboz mozgatása
	 * 
	 * @param boolean $isForward Ha igaz, akkor előre (csökken a sorszáma) mozgatja.
	 */
	private function action_move($isForward)
	{
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;
			
		$id = FunctionLibrary::getGetValue("id");

		if(!is_null($id) && TextUtil::isStringInteger($id))
		{
			$id = intval($id);

			// szedjük vissza a rekordot! ez tömböt ad, tudod!
			$boxRecord = AdminDBHelper::getBox($id);
			if(is_null($boxRecord))
			{
				// nincs mit törölni!
				handleError(TextHandler::getText('bx_err_boxnotfound'), $this->getListPageLink());
				exit();
			}

			try {
				AdminDBHelper::moveBox($boxRecord, $isForward);
					
				handleSuccess(TextHandler::getText("bx_moved"), $this->getListPageLink());
				exit();
			} catch (Exception $e) {
				$logErrorString = "moving box id=$id failed: ".$e->getMessage();
				$errorStrings = array($e->getMessage());
			}
		}
		else
		{
			$logErrorString = "required request parameter 'id' is missing or malformed";
		}
			
		Log::error('following errors occured during operation:'.$logErrorString);
		handleError(TextHandler::getParsedText('bx_err_move_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
	}

	private function action_moveForward() {
		$this->action_move(true);
	}

	private function action_moveBackward() {
		$this->action_move(false);
	}

	private function action_editBoxTabList() {
		// EDITBOXTABLIST_TEMPLATE		
	}

}

?>
